# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.http import JsonResponse
import json
import time
# 引入鉴权装饰器
from vue_app.utils.auth_permission import auth_permission_require
# 引入数据模型
from vue_app.models import DeviceMgrTable, DeviceDatasTable
# 引入序列化器
from django.core import serializers

# 初始化监视器面板
@auth_permission_require('')
def initDataWall(request):
    # response
    response = {}
    # data
    data = json.loads(request.body)
    deviceID = data.get("deviceID", "")
    # 选取数据
    user = request.user
    # filter
    if DeviceMgrTable.objects.filter(user_id=user.id, device_id=deviceID).exists():
        # 存在
        device = DeviceMgrTable.objects.get(user_id=user.id, device_id=deviceID)
        # # 序列化
        # device_serialize = serializers.serialize("json", device)
        # # 反序列化
        # device_json = json.loads(device_serialize)
        response.update({"opcode": 1, "deviceID": device.device_id})
    else:
        # 不存在
        response.update({"opcode": 0})
    response.update({"code": 20000})
    return JsonResponse(response)

# 图表数据请求 ver1.0
@auth_permission_require('')
def dataWall(request):
    print(request)
    # response
    response = {}
    # data
    data = json.loads(request.body)
    # device id
    device_id = data
    response.update({"ct": data})
    # 读数据库数据
    device_data_latest_10 = DeviceDatasTable.objects.filter(device_id=str(device_id))
    length = device_data_latest_10.count()
    device_data_latest_10 = device_data_latest_10.order_by("timestamp")[length-10:length]
    # 序列化
    device_data_latest_10 = serializers.serialize("json", device_data_latest_10)
    # 反序列化
    device_data_latest_10 = json.loads(device_data_latest_10)
    # 精简
    device_data_latest_10 = [d["fields"] for d in device_data_latest_10]
    # 时间戳转换
    for index, e in enumerate(device_data_latest_10):
        e.update({"date_ts": time.strftime("%Y-%m-%d\n%H:%M:%S", time.localtime(e.get("timestamp", 0)))})
    # 选取数据
    response.update({"device_datas": device_data_latest_10})
    pass
    response.update({"code": 20000})
    return JsonResponse(response)